source("./function_code/relabel_vars.R")


battleCoefPlot = function(model1, model2, fileID) {
  
  # Get coefficients and SEs
  batcoef = model1[,"Estimate"]
  batse = model1[,"Std. Error"]
  batcoef2 = model2[,"Estimate"]
  batse2 = model2[,"Std. Error"]
  
  # Create data
  batData = data.frame(vars=names(batcoef), coef=batcoef, se=batse)
  batData$lower95 = batData$coef - 1.96*batData$se
  batData$upper95 = batData$coef + 1.96*batData$se
  batData$model = "All"
  batData = batData %>% filter(vars!="logBattles:logDayNum")
  batData = batData %>% filter(vars!="AOA:logDayNum")
  
  batData2 = data.frame(vars=names(batcoef2), coef=batcoef2, se=batse2)
  batData2$lower95 = batData2$coef - 1.96*batData2$se
  batData2$upper95 = batData2$coef + 1.96*batData2$se
  batData2$model = "Split"
  batData2 = batData2 %>% filter(vars!="logBattles:logDayNum")
  batData2 = batData2 %>% filter(vars!="AOA:logDayNum")
  
  bdata = rbind(batData, batData2)
  
  # Rename variables
  bdata = relabelVars(bdata)
  
  # Remove irrelevant items
  bdata = bdata %>% filter(!grepl("\\:|Intercept|warName", vars)) %>% drop_na(vars)
  
  # Rearrange
  bdata$vars = factor(bdata$vars, 
                      levels = c("All negotiation", "Internal\nnegotiation", "External\nnegotiation", 
                                 "Ceasefire", 
                                 "Recent\nimbalance", "Overall\nimbalance", 
                                 "Issue salience", "Contiguity", "CINC ratio", "DOE score", "Democratic\ninitiator",
                                 "Major power", "Nuclear", "Number of states",
                                 "Major allies",
                                 "Opp. diplomatic\nrepresentation",
                                 "Completed\nbattles",
                                 "Active\nbattle trend",
                                 "Inconsistency",
                                 "Post-1945"))
  
  # Statistical significance  
  bdata$signif = ifelse(bdata$lower95 > 0 | bdata$upper95 < 0, "Yes", "No")
  
  # Generate coefficient plot
  batPlot = ggplot(bdata, aes(coef, fct_rev(vars))) + geom_vline(xintercept=0, linetype=2) + 
    geom_pointrange(aes(xmin=lower95, xmax=upper95, color=fct_rev(model), shape=signif), position=position_dodge(width=0.6)) + 
    theme_bw() + xlab("Coefficient estimate") +
    scale_color_manual("Model", breaks=c("All", "Split"), 
                       labels=c("All", "Disaggregated"),
                       values=c("gray10", "gray60")) +
    scale_shape_manual("Statistically\nsignificant (95%)", values=c(16, 15)) +
    theme(legend.position="bottom", 
          legend.direction = "vertical") +
    ylab("") +
    guides(color = guide_legend(order=1),
           shape = guide_legend(order=2))
  
  print(batPlot)
  
  # Make file name
  fn = paste0("./figures/battleCoefPlot", fileID, ".pdf")
  
  # Create file
  ggsave(fn, width=4.5, height=7)
}
